package com.qire.manhua.model.viewModel.impl;

import android.view.View;
import android.widget.BaseAdapter;

import com.qire.common.basic.ObjectUtil;
import com.qire.common.basic.StringUtil;
import com.qire.common.collect.ListUtil;
import com.qire.common.support.SmartRefreshViewModel;
import com.qire.common.support.base.IViewModel;
import com.qire.common.widget.adapter.auto.AutoVariable;
import com.qire.common.widget.adapter.auto.SummerBindAdapter;
import com.qire.common.widget.adapter.auto.SummerRecyclerBindAdapter;
import com.qire.common.widget.adapter.auto.annotation.AdapterEntityBind;
import com.qire.manhua.BR;
import com.qire.manhua.R;
import com.qire.manhua.controller.ClassificationController;
import com.qire.manhua.dal.service.ClassificationService;
import com.qire.manhua.databinding.LayoutHomeClassificationItemComicBinding;
import com.qire.manhua.databinding.LayoutHomeClassificationItemTagBinding;
import com.qire.manhua.model.entity.ComicBookEntity;
import com.qire.manhua.model.enumeration.Classification.FeeType;
import com.qire.manhua.model.enumeration.Classification.StateType;
import com.qire.manhua.model.enumeration.Classification.SortType;
import com.qire.manhua.model.enumeration.Classification.FoldState;

import java.util.ArrayList;

import androidx.databinding.BaseObservable;
import androidx.databinding.Bindable;
import androidx.lifecycle.MutableLiveData;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView.Adapter;
import androidx.recyclerview.widget.RecyclerView.LayoutManager;

/**
 * 首页-分类页
 */
public class ClassificationViewModel extends SmartRefreshViewModel<IViewModel> {

    private ClassificationService classificationService = new ClassificationService(this);

    /** 分类标签列表 */
    private final ArrayList<ClassifiedTagItemViewModel> classifiedTagList = new ArrayList<>(12);
    /** 分类标签数据适配器 */
    private final SummerBindAdapter<ClassifiedTagItemViewModel> classifiedTagAdapter = new SummerBindAdapter<>(classifiedTagList);

    /** 分类漫画列表 */
    private final ArrayList<ClassifiedComicItemViewModel> classifiedComicList = new ArrayList<>();
    /** 分类漫画数据适配器 */
    private final SummerRecyclerBindAdapter<ClassifiedComicItemViewModel> classifiedComicAdapter = new SummerRecyclerBindAdapter(classifiedComicList);

    // 额外默认选项，全选
    private final ClassifiedTagItemViewModel defaultClassifiedTag = new ClassifiedTagItemViewModel("all", "全部");

    private ClassifiedTagItemViewModel selectedClassifiedTag;

    private int     pageNo  = 1;

    //region    #附加管理 begin
    /**
     * 附加属性绑定
     */
    public void onAddition(ClassificationController controller) {
        classifiedTagAdapter.setEventProcess(controller);
        classifiedComicAdapter.setEventProcess(controller);
        refreshUI();
    }

    /**
     * 清理函数，在Activity退出时，ViewModel生命周期到期会被回收，调用该事件，页面由于切换、横竖屏转换、内存回收等情况并不会影响到ViewModel的生命周期。
     */
    @Override
    protected void onCleared() {
        super.onCleared();
        classifiedTagAdapter.setEventProcess(null);
        classifiedComicAdapter.setEventProcess(null);
    }
    //endregion #附加管理 end


    //region    #业务数据处理 begin

    private void resetPage(){
        pageNo = 1;
    }

    public void nextPage(){
        pageNo += 1;
    }

    public void loadClassifiedComicList() {
        resetPage();
        clearClassifiedComicList();
        loadMoreClassifiedComicList();
    }

    public void loadMoreClassifiedComicList() {
        String classifiedTagId  = ObjectUtil.isNull(selectedClassifiedTag) ? "all" : selectedClassifiedTag.id();
        String feeType   = feeType().type;
        String stateType = stateType().type;
        String sortType  = sortType().type;
        classificationService.fetchClassifiedComicList(classifiedTagId, feeType, stateType, sortType, pageNo);
    }

    public void clearClassifiedComicList() {
        classifiedComicAdapter.notifyItemRangeRemoved(0, classifiedComicList.size());
        classifiedComicList.clear();
    }

    public void addClassifiedComicItem(int comicId, String comicTitle, String shortTitle, String comicAuthor,
                                       String coverImage, String coverFloatTips, String updateInfo, int popularityValue) {
        classifiedComicList.add(new ClassifiedComicItemViewModel(comicId, comicTitle, shortTitle, comicAuthor, coverImage, coverFloatTips, updateInfo, popularityValue));
    }

    public void refreshClassifiedComicAdapter() {
        classifiedComicAdapter.notifyItemChanged(0, "full");
    }

    public void loadAllClassifiedTag() {
        classificationService.loadAllCategoryTag();
    }

    public void clearClassifiedTagList() {
        classifiedTagList.clear();
        classifiedTagList.add(defaultClassifiedTag);
        if(selectedClassifiedTag == null) {
            defaultClassifiedTag.toggle();
        }
    }

    public void addClassifiedTagItem(String id, String name) {
        ClassifiedTagItemViewModel itemViewModel = new ClassifiedTagItemViewModel(id, name);
        classifiedTagList.add(itemViewModel);
        if(selectedClassifiedTag.equalsId(itemViewModel)) {
            itemViewModel.toggle();
        }
    }

    public void refreshClassifiedTagAdapter() {
        classifiedTagAdapter.notifyDataSetChanged();
    }

    public void gotoTagTabBy(String tagId) {
        for(ClassifiedTagItemViewModel tagItemViewModel : classifiedTagList) {
            if(tagItemViewModel.equalsId(tagId)) {
                tagItemViewModel.toggle();
                return;
            }
        }
        defaultClassifiedTag.toggle();
    }

    //endregion #业务数据处理 end


    // region #UI操作

    public void refreshUI() {
        refreshEmptyDataUI();
        toggleFold(FoldState.UNFOLD);
        changeFeeType(FeeType.ALL);
        changeStateType(StateType.ALL);
        changeSortType(SortType.RECOMMEND);
    }

    public void refreshEmptyDataUI() {
        boolean isComicEmpty = ListUtil.isEmpty(classifiedComicList);
        set("emptyDataPanelVisible", isComicEmpty ? View.VISIBLE : View.GONE);
    }

    public boolean isFold() {
        return getToValue("foldState") == FoldState.FOLD;
    }
    public FeeType feeType() {
        return getToValue("feeType");
    }
    public StateType stateType() {
        return getToValue("stateType");
    }
    public SortType sortType() {
        return getToValue("sortType");
    }
    public ClassifiedTagItemViewModel defaultClassifiedTag() {
        return defaultClassifiedTag;
    }

    public void toggleFold(FoldState foldState) {
        set("foldState", foldState);
    }

    public void changeFeeType(FeeType feeType) {
        FeeType type = feeType();
        if(ObjectUtil.notEquals(type, feeType)) {
            set("feeType", feeType);
            if(ObjectUtil.nonNull(type)) {
                loadClassifiedComicList();
            }
        }
    }

    public void changeStateType(StateType stateType) {
        StateType type = stateType();
        if(ObjectUtil.notEquals(type, stateType)) {
            set("stateType", stateType);
            if(ObjectUtil.nonNull(type)) {
                loadClassifiedComicList();
            }
        }
    }

    public void changeSortType(SortType sortType) {
        SortType type = sortType();
        if(ObjectUtil.notEquals(type, sortType)) {
            set("sortType", sortType);
            if(ObjectUtil.nonNull(type)) {
                loadClassifiedComicList();
            }
        }
    }

    private void changeClassifiedTag(ClassifiedTagItemViewModel classifiedTag) {
        if(ObjectUtil.isNull(classifiedTag)) {
            set("currentClassifiedNameVisible", View.GONE);
            set("currentClassifiedName", "");
            return;
        }

        if(classifiedTag.equals(selectedClassifiedTag)) {
            return;
        }

        if(ObjectUtil.nonNull(this.selectedClassifiedTag)) {
            this.selectedClassifiedTag.setChoose(false);
        }

        classifiedTag.setChoose(true);
        this.selectedClassifiedTag = classifiedTag;

        set("currentClassifiedNameVisible", classifiedTag.equalsId("all") ? View.GONE : View.VISIBLE);
        set("currentClassifiedName", classifiedTag.name);
        loadClassifiedComicList();
    }

    // endregion #UI操作


    // region #UI属性绑定
    public MutableLiveData<FeeType> getFeeType() {
        return get("feeType");
    }

    public MutableLiveData<StateType> getStateType() {
        return get("stateType");
    }

    public MutableLiveData<SortType> getSortType() {
        return get("sortType");
    }

    public MutableLiveData<FoldState> getFoldState() {
        return get("foldState");
    }

    public MutableLiveData<Integer> getCurrentClassifiedNameVisible() {
        return get("currentClassifiedNameVisible");
    }

    public MutableLiveData<CharSequence> getCurrentClassifiedName() {
        return get("currentClassifiedName");
    }

    public MutableLiveData<Integer> getEmptyDataPanelVisible() {
        return get("emptyDataPanelVisible");
    }


    public BaseAdapter getClassifiedTagAdapter(){
        return classifiedTagAdapter;
    }

    public LayoutManager getClassifiedComicLayoutManager(){
        return new LinearLayoutManager(null);
    }

    public Adapter getClassifiedComicAdapter(){
        return classifiedComicAdapter;
    }

    // endregion


    @AdapterEntityBind(viewRid = R.layout.layout_home_classification_item_tag)
    public class ClassifiedTagItemViewModel extends BaseObservable implements AutoVariable<LayoutHomeClassificationItemTagBinding> {

        private final String id;
        private final String name;

        private boolean isChoose = false;

        public ClassifiedTagItemViewModel(String id, String name) {
            this.id = id;
            this.name = name;
        }

        @Override
        public void bindVariable(LayoutHomeClassificationItemTagBinding viewBind) {
            viewBind.setClassifiedTagItemViewModel(this);
        }

        public String id() {
            return id;
        }

        public boolean equalsId(String tagId) {
            return this.id.equals(tagId);
        }

        public boolean equalsId(ClassifiedTagItemViewModel tagItem) {
            return tagItem != null ? equalsId(tagItem.id) : false;
        }

        public void setChoose(boolean isChoose) {
            this.isChoose = isChoose;
            notifyPropertyChanged(BR.checked);
            notifyPropertyChanged(BR.indicatorVisible);
        }

        public void toggle() {
            changeClassifiedTag(this);
        }

        @Bindable
        public boolean getChecked() {
            return isChoose;
        }

        @Bindable
        public CharSequence getName() {
            return name;
        }

        @Bindable
        public int getIndicatorVisible(){
            return isChoose ? View.VISIBLE : View.INVISIBLE;
        }

    }

    @AdapterEntityBind(viewRid = R.layout.layout_home_classification_item_comic)
    public class ClassifiedComicItemViewModel extends BaseObservable implements AutoVariable<LayoutHomeClassificationItemComicBinding> {

        private final int    comicId;
        private final String comicTitle;
        private final String shortTitle;
        private final String comicAuthor;
        private final String coverImage;
        private final String coverFloatTips;
        private final String updateInfo;
        private final int    popularityValue;

        public ClassifiedComicItemViewModel(int comicId, String comicTitle, String shortTitle, String comicAuthor, String coverImage, String coverFloatTips, String updateInfo, int popularityValue){
            this.comicId        = comicId;
            this.comicTitle     = comicTitle;
            this.shortTitle     = shortTitle;
            this.comicAuthor    = comicAuthor;
            this.coverImage     = coverImage;
            this.coverFloatTips = coverFloatTips;
            this.updateInfo     = updateInfo;
            this.popularityValue= popularityValue;
        }

        public int comicId() {
            return comicId;
        }
        public ComicBookEntity toComicBookEntity(){
            return new ComicBookEntity(comicId,comicTitle);
        }

        @Override
        public void bindVariable(LayoutHomeClassificationItemComicBinding viewBind) {
            viewBind.setClassifiedComicItemViewModel(this);
        }

        @Bindable
        public String getCoverImage(){
            return coverImage;
        }
        @Bindable
        public CharSequence getCoverFloatTips(){
            return coverFloatTips;
        }
        @Bindable
        public CharSequence getComicTitle(){
            return comicTitle;
        }
        @Bindable
        public CharSequence getComicAuthor(){
            return comicAuthor;
        }
        @Bindable
        public CharSequence getShortTitle(){
            return shortTitle;
        }
        @Bindable
        public CharSequence getUpdateInfo(){
            return updateInfo;
        }
        @Bindable
        public CharSequence getPopularityValue(){
            return "人气值：" + StringUtil.toSymbol(popularityValue);
        }

    }


}
